<!-- 创建专栏下的文章 -->
<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
     <Uploader action="/upload" 
        :beforeUpload="handerBeforeUploader" 
        @file-uploader="onFileUploaded"
        class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4">
        <h2>点击上传头图</h2>
        <template #loading>
          <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
       </template>
        <template #uploaded="{uploaderData}">
          <div class="uploaded-area">
            <img :src="uploaderData.data.url" v-if="uploaderData">
            <h3>点击重新上传</h3>
        </div>
        </template>
      </Uploader>

    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules" v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          tagType="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}
</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { GlobalDataProps, PostProps, ResponseType, ImageProps  } from '@/store/index'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import Uploader from '@/components/Uploader.vue'
import { beforeUploadCheck } from '@/utils/helper'
import createMessage from '@/components/CreateMessage'
export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm,
    Uploader,
  },
  setup() {
    const uploadedData = ref()
    const titleVal = ref('')
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const store = useStore<GlobalDataProps>()
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ];

    let imageId = ''
    const handerBeforeUploader = (file: File) => {
      console.log("file==", file)
        const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
        console.log("result==", result)
        const { passed, error } = result
        if (error === 'format') {
          createMessage('上传图片只能是 JPG/PNG 格式!', 'error')
        }
        if (error === 'size') {
          createMessage('上传图片大小不能超过 1Mb', 'error')
        }
        return passed
    }
    const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
     // imageId = rawData.data._id as string;//
      if(rawData.data._id) {
        imageId = rawData.data._id;
      }
    }
    const onFormSubmit = (result: boolean) => {
      if (result) {
         const {column, _id} = store.state.user; 
         // columnId： number | undefined,  可能是undefined类型（ts好处，提前推断出未登录成功前，columnId有可能是undefined）
         if( column ) {
             const newPost: PostProps = {
                _id: new Date().getTime() + "",
                column,
                title: titleVal.value,
                content: contentVal.value,
                createdAt: new Date().toLocaleString(),
                author: _id,
             }
             
             if(imageId) {
               newPost.image = imageId
             }

            //  store.commit("createPosts", newPost)
            //  router.push({name: 'columnDetail', params: {id: column }})

            store.dispatch("createPosts", newPost).then(() => {
                createMessage('发表成功，2秒后跳转到文章', 'success', 2000)
                setTimeout(() => {
                  router.push({ name: 'columnDetail', params: { id: column } })
                }, 2000)
            })
         }
      }
    }

    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      uploadedData,
      isEditMode,

      handerBeforeUploader,
      onFileUploaded
    }
  }
})
</script>
<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
